<?php
namespace Admin\Controller;

use Think\Controller;

class LoginController extends Controller
{
    public function login()
    {
        $adm_pv_db = M('adm_pv', '', 'XYC');
        $data['user_ip'] = getIP();
        $data['ctime'] = time();
        $data['content'] = '登录页面：' . $_SERVER['HTTP_USER_AGENT'];
        $adm_pv_db->add($data);
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla') === false) {
            header("location:https://www.baidu.com/");
            exit();
        }
        if ($_SESSION['phone'] && $_SESSION['id']) {
            $this->redirect('Index/index');
        }

        $this->display();
    }

    public function login_test()
    {
        $adm_pv_db = M('adm_pv', '', 'XYC');
        $data['user_ip'] = getIP();
        $data['ctime'] = time();
        $data['content'] = '登录页面：' . $_SERVER['HTTP_USER_AGENT'];
        $adm_pv_db->add($data);
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla') === false) {
            header("location:https://www.baidu.com/");
            exit();
        }
        if ($_SESSION['phone'] && $_SESSION['id']) {
            $this->redirect('Index/index');
        }
        $this->display();
    }

    /**
     * 用户登录验证
     */
    public function get_login()
    {
        if (!empty($_POST)) {
            $info = D('Admin');
            $account = I('account');
            $pwd = I('pwd');
            $redis = MycommonController::mk_redis();

            $pwd = set_pwd($account, $pwd);
            //上一次登录地点
            $pre_address=M('login_log','','XYC')->WHERE(['account'=>$account])->ORDER('id desc')->getField('location');
//            $redis->delete(RedisPrefixController::LOGIN_COUNT . $account);//测试用
                //1小时内登录次数大于等于6次或者与上一次登录地点不一致则需要验证码

            if ($redis->get(RedisPrefixController::LOGIN_COUNT . $account) >= '6' || ($pre_address!=get_address(getIP()) && !empty($pre_address)) && $account!='xinyongcha' && $account!='ceshi8-8') {
                $verify = I('verify');
                $adm_verify = $redis->get(RedisPrefixController::ADM_VERIFY . $account);
                if (empty($adm_verify) || $adm_verify != $verify) {
                    MycommonController::ajax('1003', '验证码有误', 'error');
                }
            }

            $res = $info->check_login($account, $pwd);
            $param = RedisPrefixController::LOGIN . $account;
            if ($redis->get($param) >= 3 && $account!='ceshi8-8') {
                MycommonController::ajax('1002', '密码错误次数超过三次，请1小时之后再登录', 'error');
            }
            if (!is_array($res)) {
                $redis->incr($param);
                if ($redis->get($param) == '3') {
                    $redis->expire($param, 3600);
                    add_login_error_log($account);
                }
            }

            if (!is_array($res)) {
                MycommonController::ajax('1002', $res, 'error');
            } else {
                if (!empty($redis->get($param))) {
                    $redis->delete($param);
                }
//                //记录登录频次
                $param=RedisPrefixController::LOGIN_COUNT.$account;
                if(empty($redis->get($param))){
                    $redis->incr($param);
                    $redis->expire($param,3600);
                }else{
                    $redis->incr($param);
                }
                $redis->close();

                $role_db=M('merchant_role','','XYC');
                $admin['top_id']=$role_db->WHERE(['id'=>['in',$res['rid']]])->getField('top_id',true);
                $admin['top_id']=implode(',',array_unique(explode(',',implode(',',$admin['top_id']))));
                $admin['next_id']=$role_db->WHERE(['id'=>['in',$res['rid']]])->getField('next_id',true);
                $admin['next_id']=implode(',',array_unique(explode(',',implode(',',$admin['next_id']))));
                $admin['last_id']=$role_db->WHERE(['id'=>['in',$res['rid']]])->getField('last_id',true);
                $admin['last_id']=implode(',',array_unique(explode(',',implode(',',$admin['last_id']))));

                if(I('save')=='2'){
                    cookie('xyc_account',$res['account'],24*3600*90);
                    cookie('xyc_pwd',I('pwd'),24*3600*90);
                    cookie('xyc_save','2',24*3600*90);
                }else{
                    cookie('xyc_account',null);
                    cookie('xyc_pwd',null);
                    cookie('xyc_save',null);
                }
                cookie('xycshop'.$res['account'],'1',3600*3);
                session('id', $res['id']);
                session('account', $res['account']);
                session('mobile', $res['mobile']);
                session('name', $res['name']);
                session('rid', $res['rid']);
                session('is_hide', $res['is_hide']);
                session('chan_id', $res['chan_id']);
                session('shop_identifier', $res['shop_idenfier']);
                session('login_time', date('Y-m-d H:i:s', time()));
                session('xycshop'.$res['account'],$admin['top_id'].'|'.$admin['next_id'].'|'.$admin['last_id']);
                add_login_log($res['shop_idenfier'], $res['account'], $res['name']);
                MycommonController::ajax('1001', '登录成功');
            }
        }
    }


    /**
     * 发送验证码
     */
    public function send_verify()
    {
        if (!empty($_POST)) {
            $admin_db = D('Admin');
            $redis = MycommonController::mk_redis();
            $verify = new \Think\Verify();
            $verify->useImgBg = true;

            $account = I('account');
            $img_verify = I('img_verify');
            $res = $verify->check($img_verify, getIP());
            if ($res !== true) {
                MycommonController::ajax('1002', '图形验证码有误，请重新输入');
            }
            $mobile = $admin_db->WHERE(['account' => $account])->getField('mobile');
            $param = RedisPrefixController::VERIFY_CODE . $account;
            if ($redis->get($param) >= '5') {
                MycommonController::ajax('1002', '错误次数过多，请24小时之后再尝试');
            }
            if (empty($mobile)) {
                $redis->incr($param);
                if ($redis->get($param) == '5') {
                    $redis->expire($param, 3600 * 24);
                    add_login_error_log($mobile, '发送验证码错误五次');
                }
                MycommonController::ajax('1002', '账号有误');
            }
            $sign=M('merchant','','XYC')->JOIN("m JOIN shopkeeper s ON m.shop_identifier=s.shop_idenfier")->WHERE(['s.account'=>$account])->getField('m.merchant_name');
            $num = rand(100000, 999999);
            $res = MycommonController::cl_sms($mobile, '尊敬的用户，您的验证码为' . $num . '，请于180秒内输入，如非本人操作，请忽略此短信。',$sign);
            if ($res === true) {
                $redis->set(RedisPrefixController::ADM_VERIFY.$account,$num);
                $redis->expire(RedisPrefixController::ADM_VERIFY.$account,180);
                if (!empty($redis->get($param))) {
                    $redis->delete($param);
                }
                MycommonController::ajax('1001', '发送成功');
            } else {
                MycommonController::ajax('1002', '发送失败');
            }
        }
    }

    /**
     * 生成图形验证码
     */
    public function mk_verify()
    {
        header("Access-Control-Allow-Origin: *");
        ob_clean();
        $config = array(
            'imageW'=>'175',//宽度
            'imageH'=>'55',//高度
            'fontSize'=>'25',//字体大小
            'length' => 4,     // 验证码位数
            'useNoise' => false, // 关闭验证码杂点
            'useCurve' => false, // 关闭验证码杂点
        );
        $Verify = new \Think\Verify($config);
        $Verify->useImgBg = true;
        $ip = getIP();
        $Verify->entry($ip);
    }

    /**
     * 用户密码修改
     */
    public function modify()
    {
        if (empty($_SESSION['id'])) {
            $this->redirect('Login/login');
        }
        $this->display();
    }

    /**
     * 修改密码操作
     */
    public function modify_pwd()
    {
        if (empty($_SESSION['id'])) $this->redirect('Login/login');
        if (!empty($_POST)) {
            $info = D('Admin');
            $old_pwd = I('old_pwd');
            $new_pwd = I('new_pwd');
            $res = $info->check_modify_pwd($old_pwd, $new_pwd);
            if (is_array($res)) {
                $content = $res['account'].'修改登录密码';
                add_control_log($_SESSION['shop_identifier'],$_SESSION['account'],$content,'3');
                session(null);
                MycommonController::ajax('1001', '修改成功');
            } else {
                MycommonController::ajax('1002', $res, 'error');
            }
        }
    }

    /**
     * 忘记密码页面
     */
    public function forget_pwd(){
        $this->display();
    }

    /**
     * 忘记密码修改
     */
    public function forget_password(){
        if(!empty($_POST)){
            $redis = MycommonController::mk_redis();
            $info = D('Admin');
            $account = I('account');
            $pwd = I('new_pwd');
            if(preg_match_all("/^(?!^\\d+$)(?!^[A-Z]+$)(?!^[_#@]+$).{6,}/",$pwd)=='0'){
                MycommonController::ajax('1002', '密码必须同时包含数字和字母', 'error');
            }
            $pwd = set_pwd($account, $pwd);
            if(empty($info->WHERE(['account'=>$account])->getField('id'))){
                MycommonController::ajax('1002', '账号有误', 'error');
            }
            $verify = I('verify');
            $adm_verify = $redis->get(RedisPrefixController::ADM_VERIFY . $account);
            if (empty($adm_verify) || $adm_verify != $verify) {
                MycommonController::ajax('1002', '验证码有误', 'error');
            }
            $res=$info->WHERE(['account'=>$account])->setField('password',$pwd);
            if($res!==false){
                session('id', null);
                session('mobile', null);
                session('account', null);
                session('name', null);
                session('rid', null);
                session('login_time', null);
                session(null);
                MycommonController::ajax('1001', '密码重置成功');
            }else{
                MycommonController::ajax('1002', '操作失败', 'error');
            }


        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        session('id', null);
        session('mobile', null);
        session('account', null);
        session('name', null);
        session('rid', null);
        session('login_time', null);
        session(null);
        $this->redirect('Login/login');
    }

    public function _empty()
    {
        $this->redirect('Alerterror/error404');
    }
}